<?php
/**
 * Created by PhpStorm.
 * User: Winter
 * Date: 2020/8/11 0011
 * Time: 15:35
 */
namespace app\api\controller\alipay;

use app\models\store\StoreOrder;
use app\models\system\SystemGroupData;
use app\models\user\User;
use app\models\user\UserRecharge;
use crmeb\repositories\PaymentRepositories;

class IndexController{

    public $_config = [
        // 沙箱模式
        'debug'       => false,
        // 应用ID
//        'appid'       => '2021001168673258',
//        // 支付宝公钥(1行填写)
//        'public_key'  => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkdXEblroO7oA1ZM/CWrmUyIh83bbKMKoaZRoTTX80MoDbaw8yUFQJGWhxF8YnNdNXPl8iBINMeqiy1HUNzfIMwSMY0nRfZwMqIho4qd5mHLXjlAN8jDiQzUKzBgTzQuNOdM12M/A70EUweLw6uRyi72eQzOr0Bv/Z4a3NaSGyR801f77Ga3wW/+UKpE5Y4wCM6FAccGVS3sBh1VWGYL2lmdNPQbVxeLwx7SWaXyOVa32zxKqhEXgKnxa/0RLYPBJfQAfZFb8SOY9d54I94trncY9Q9kGw+JszKNjkEytzbLI55tRbkeen9hgM6CnfLhXPOS9LkojTneKjSkcxZGozQIDAQAB',
//        // 支付宝私钥(1行填写)
//        'private_key' => 'MIIEpAIBAAKCAQEAxnSJ4TUds96orMnIvvLRipuOqdMsD6/mGfAejVs5pk14T8YiMuRw1sVgs7aOGvrcOXvxIa5iSt/vyOJ2vfIIIjCJF6JTEER9bLTNoBl0XQWAWO2XrJd3BfKjnGXed58Zv6LZYBSCUL9y5BBiQag7kHVytp+K5j8xvQlXpmVIBXwg7MmxtLqe6U33kIZ93EDFhRL/CUIS6IuNt20XElXKg6JtrZY3k7tj25VrHZtM5hpM9qrFssierELIgoP5vf4KiWbDzcA//8eSzMxtUwVU2OSi1XOW0WXHzA7Kg+qv8WT3m22RA1XvIxFplWxtDtNlr5n9M6h35h1KH9+jshfUawIDAQABAoIBAQCPC9uCuG2jhEAi5APOF2qQtVXc9XkSCaEbWyg6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ztIWTRLDnZpuetTOFka1qfcRlCBPAW5pZMKw+Apdla93ptkYAtYOjKdP5oO3SmeNJjtyaUFZEIu67lipN1fbenw0hSR3jzUJIQQ==',
//        // 支付成功通知地址
        'notify_url'  => 'http://test.user2006.com/api/notify_url', // 可以应用的时候配置哦
        // 网页支付回跳地址
        'return_url'  => 'http://test.user2006.com/api/return_url', // 可以应用的时候配置哦
    ];

    /**
     * 订单支付宝支付
     */
    public function get_order_signature(){
        $order_id   = request()->param('order_id');
        $order_info = StoreOrder::get(['order_id'=>$order_id]);
        $mer_id     = $order_info['mer_id'];
        $config     = $this->_config;
        $config['appid'] = sys_config_client('alipay_appid',$mer_id);
        $config['public_key'] = sys_config_client('alipay_public_key',$mer_id);
        $config['private_key'] = sys_config_client('alipay_private_key',$mer_id);
        if(!$order_id || !$order_info){
            return app('json')->fail('参数有误!');
        }
        try {
            // 实例支付对象
            $pay = \We::AliPayWap($config);
            // $pay = new \AliPay\Wap($config);

            $body = json_encode(['order_id'=>$order_id,'pay_type'=>1,'mer_id'=>$mer_id]);
            // 参考链接：https://docs.open.alipay.com/api_1/alipay.trade.wap.pay
            $result = $pay->apply([
                'out_trade_no' => time(), // 商户订单号
                'total_amount' => $order_info['pay_price'],    // 支付金额
                'subject'      => '订单支付', // 支付订单描述
                'body'      => $body, // 支付订单描述
            ]);

            echo $result; // 直接输出HTML（提交表单跳转)

        } catch (Exception $e) {

            // 异常处理
            echo $e->getMessage();

        }
    }


    /**
     * 充值支付宝支付
     */
    public function get_recharge_signature(){
        $config = $this->_config;
        $recharge_id  = request()->param('recharge_id');
        $uid          = request()->param('uid');
        $price        = request()->param('price');
        if(!$recharge_id || !$uid || !$price){
            return app('json')->fail('参数有误!');
        }
        $user_info     = User::get(['uid'=>$uid]);
        $mer_id        = $user_info['mer_id'];
        $config['appid']       = sys_config_client('alipay_appid',$mer_id);
        $config['public_key']  = sys_config_client('alipay_public_key',$mer_id);
        $config['private_key'] = sys_config_client('alipay_private_key',$mer_id);
        $paid_price = 0;
        if ($recharge_id) {
            $data = SystemGroupData::getDateValue($recharge_id);
            if ($data === false) {
                return app('json')->fail('您选择的充值方式已下架!');
            } else {
                $paid_price = $data['give_money'] ?? 0;
            }
        }
        $rechargeOrder = UserRecharge::addRecharge($uid, $price, 'alipay', $paid_price,0,$mer_id);
        $order_id      = $rechargeOrder->order_id;
        try {
            // 实例支付对象
            $pay = \We::AliPayWap($config);
            // $pay = new \AliPay\Wap($config);

            $body = json_encode(['order_id'=>$order_id,'pay_type'=>2,'mer_id'=>$mer_id]);
            // 参考链接：https://docs.open.alipay.com/api_1/alipay.trade.wap.pay
            $result = $pay->apply([
                'out_trade_no' => time(), // 商户订单号
                'total_amount' => $price,    // 支付金额
                'subject'      => '用户充值', // 支付订单描述
                'body'      => $body, // 支付订单描述
            ]);

            echo $result; // 直接输出HTML（提交表单跳转)

        } catch (Exception $e) {

            // 异常处理
            echo $e->getMessage();

        }
    }

    /**
     * 支付成功跳转
     */
    public function  return_url(){
        echo "支付成功";
    }


    /**
     * 支付异步回调
     */
    public function  notify_url(){
        $config = $this->_config;

        $data_origin = request()->post();
        $body_arr    = json_decode($data_origin['body'],true);
        $mer_id      = $body_arr['mer_id'];
        $config['appid'] = sys_config_client('alipay_appid',$mer_id);
        $config['public_key'] = sys_config_client('alipay_public_key',$mer_id);
        $config['private_key'] = sys_config_client('alipay_private_key',$mer_id);
        $pay = new \AliPay\Wap($config);
        $data = $pay->notify();
        $json_data = json_encode($data);
        file_put_contents('alipay.txt',$json_data.PHP_EOL,8);
        $body     = $data['body'];
        $body_arr = json_decode($body,true);
        $order_id = $body_arr['order_id'];
        $res = false;
        if($body_arr['pay_type']==1){ //订单
            $res =  PaymentRepositories::alipayProduct($order_id);
        }elseif ($body_arr['pay_type']==2){//充值
            $res =  PaymentRepositories::wechatUserRecharge($order_id);
        }
        if($res){
            echo "success";
        }
    }
}